package cn.scw.framework.security.service;

import cn.scw.common.constant.Constants;
import cn.scw.common.exception.CustomException;
import cn.scw.common.exception.user.CaptchaException;
import cn.scw.common.exception.user.CaptchaExpireException;
import cn.scw.common.exception.user.UserPasswordNotMatchException;
import cn.scw.common.utils.MessageUtils;
import cn.scw.common.utils.SecurityUtils;
import cn.scw.common.utils.StringUtils;
import cn.scw.common.utils.UUIDUtils;
import cn.scw.common.utils.http.HttpUtils;
import cn.scw.common.utils.sign.Base64;
import cn.scw.framework.manager.AsyncManager;
import cn.scw.framework.manager.factory.AsyncFactory;
import cn.scw.framework.redis.RedisCache;
import cn.scw.framework.security.LoginUser;
import cn.scw.framework.web.domain.AjaxResult;
import cn.scw.project.facility.service.IFacFacilityService;
import cn.scw.project.goods.service.IGCouponUserService;
import cn.scw.project.system.domain.SysUser;
import cn.scw.project.system.domain.netework.bean.SysUserLoginReq;
import cn.scw.project.system.domain.netework.bean.SysUserPhoneReq;
import cn.scw.project.system.domain.vo.SysUserWxVo;
import cn.scw.project.system.service.ISysDealerService;
import cn.scw.project.system.service.ISysUserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ctc.wstx.util.StringUtil;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLDecoder;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;

/**
 * 登录校验方法
 *
 * @author api
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private IGCouponUserService igCouponUserService;

    @Autowired
    private IFacFacilityService iFacFacilityService;
    @Autowired
    private ISysDealerService iSysDealerService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code  验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }

    public AjaxResult wxLogin(SysUserLoginReq req) {
        if (StringUtils.isBlank(req.getOpenId()))
            throw new CustomException("登录失败");
        SysUser user = iSysUserService.selectUserByOpenId(req.getOpenId());
        if (user == null) {
            String userName = UUIDUtils.getOrderNumberByUUId();
            String password = SecurityUtils.encryptPassword("123456");
            user = new SysUser(userName, req.getNickName(), req.getAvatar(), password, req.getSex(), req.getOpenId(), req.getSessionKey());
            iSysUserService.insertUser(user);
        } else {
            user.setSessionKey(req.getSessionKey());
            iSysUserService.updateUserDelFlag(user.getUserId());
        }

        LoginUser loginUser = new LoginUser(user, permissionService.getMenuPermission(user));
        String token = tokenService.createToken(loginUser);

        SysUserWxVo sysUserWxVo = iSysUserService.getWxUserInfo(user,token);
        System.out.println("wxLogin token =" + sysUserWxVo.getToken());

        return AjaxResult.success(sysUserWxVo);
    }

    public AjaxResult getPhoneNo(SysUserPhoneReq req) {
        if (StringUtils.isBlank(req.getOpenId()))
            throw new CustomException("登录失败");
        // 被加密的数据
        byte[] dataByte = Base64.decode(req.getEncryptedData());
        // 加密秘钥
        byte[] keyByte = Base64.decode(req.getSessionKey());
        // 偏移量
        byte[] ivByte = Base64.decode(req.getIv());
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                JSONObject json =  JSONObject.parseObject(result);
                String phone = json.getString("phoneNumber");
                if(StringUtils.isNotEmpty(phone)){
                    int count =  iSysUserService.setUserPhone(req.getOpenId(),phone);
                    if(count > 0){
                        return AjaxResult.success();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error();
    }


    private static final String appId = "wxc92e328fe669df24";
    private static final String secret = "d6729ab1e4e7ba1f7c1e0539e86e40db";
    private static final String grantType = "authorization_code";


    /**
     * 获取sessionKey和openid
     *
     * @param code 验证码
     * @return 结果
     */
    private JSONObject getSessionKeyOrOpenId(String code) {

        //微信端登录code
        String param = "appid=" + appId + "&secret=" + secret + "&js_code=" + code + "&grant_type=" + grantType;
        String loginUrl = "https://api.weixin.qq.com/sns/jscode2session";
        //发送post请求读取调用微信接口获取openid用户唯一标识
        return JSON.parseObject(HttpUtils.sendGet(loginUrl, param));
    }

    public AjaxResult getWxOpenId(String code) {
        JSONObject jsonObject = this.getSessionKeyOrOpenId(code);
        if (jsonObject.get("openid") == null) {
            throw new CustomException("授权失败");
        }
        String openid = jsonObject.get("openid").toString();

        String sessionKey = jsonObject.get("session_key").toString();
        AjaxResult ajax = AjaxResult.success();

        ajax.put("openId", openid);
        ajax.put("sessionKey", sessionKey);

        return ajax;
    }
}
